package com.example.init;

import com.example.util.ConfigUtil;
import com.example.xxljob.DemoJobHandler;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.util.XxlJobRemotingUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

@Slf4j
public class XxljobUtil {
    private static XxlJobExecutor executor;

    static{
        XxljobConfig config = ConfigUtil.getConfig("xxl.job.executor", XxljobConfig.class);

        try {
            XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
            xxlJobExecutor.setAdminAddresses(config.getAddresses()); // 调度中心地址
            xxlJobExecutor.setAppname(config.getAppname()); // 执行器名称
            xxlJobExecutor.setIp(config.getIp()); // 执行器 IP
            xxlJobExecutor.setPort(config.getPort()); // 执行器端口
            xxlJobExecutor.setAccessToken(config.getAccessToken()); // 调度中心通讯 Token
            xxlJobExecutor.setLogPath(config.getLogpath()); // 日志存储路径
            xxlJobExecutor.setLogRetentionDays(config.getLogretentiondays()); // 日志保留天数

//            xxlJobExecutor.registJobHandler("demoJobHandler2", new DemoJobHandler());
//            XxljobUtil.regist("demoJobHandler2", new DemoJobHandler());
            xxlJobExecutor.start();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public static void destroy() {
        if (executor != null) {
            executor.destroy();
        }
    }

    public static <T extends IJobHandler> void regist(String name, T bean) {
        executor.registJobHandler(name, bean);
    }

    public static void print() {
        log.info("---------------" + XxljobUtil.class);
    }


    private void registerRemote() {
//        ReturnT<String> returnT =  XxlJobRemotingUtil.postBody(xxlJobProperties.getAdminAddresses() + "api/addOrUpdate", xxlJobProperties.getAccessToken(), 3, xxlJobInfo, String.class);
//        if(ReturnT.SUCCESS.getCode() == returnT.getCode()){
//            xxlJobInfo.setId(Integer.parseInt(returnT.getContent()));
//            taskJobMap.put(taskJob.getKey(),xxlJobInfo);
//        }else{
//            log.error("jobKey:{},异常：{}",taskJob.getKey(),returnT.getMsg());
//        }
    }
}